package org.gd.hellojavacore;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Mapped2 {

    /**
     * 1MB - MappedBufferLength
     */
    private static final int length = 1024;
    /**
     * times MappedByteBuffer will be used
     */
    private static final int mappingNumber = 5*1024*1024;

    public static void main(String... args) throws IOException {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("D:\\BIGFILE", "rw");
            FileChannel rach = raf.getChannel();
            MappedByteBuffer buf;
            int mappingStartPos = 0;
            for(int i = 0; i < mappingNumber; i++){
                buf = rach.map(FileChannel.MapMode.READ_WRITE, mappingStartPos, length);
                mappingStartPos += length;
                for(int j = 0; j < length; j++) {
                    buf.put((byte)'x');
                }
                buf.clear();
            }
            System.out.println("Done");
        } catch(Exception e) {
            e.printStackTrace(System.err);
            System.gc();
            System.exit(0);
        } finally {
            if (raf != null) raf.close();
        }
    }
}
